package que.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import que.app.AppV1;
import que.common.Word;
import que.util.AtguiguUtil;
import que.util.FlinkSinkUtil;

import java.time.Duration;
import java.util.Collections;
import java.util.List;

/**
 * @author Naruto
 * @description:  一人播放一次视频的数据
 *         因为数据每30s生成一条，或结束生成一条
 *        所以
 *          30左右没来同一个用户的同一个视频编号数据，则算播放一次
 * @Class_Name que.app.dwd.log.DwdTrafficVideoPlayDetail
 * @Date 2022/09/01 19:21
 */
public class DwdTrafficVideoPlayDetail extends AppV1 {

    public static void main(String[] args) {
        new DwdTrafficVideoPlayDetail().init(
                9004,
                2,
                "DwdTrafficVideoPlayDetail",
                Word.TOPIC_DWD_TRAFFIC_VIDEO
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        KeyedStream<JSONObject, String> keyedStream = stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((json, ts) -> json.getLong("ts"))
                )
                .keyBy(json -> json.getJSONObject("common").getString("uid") + "_" + json.getJSONObject("appVideo").getString("video_id"));


        keyedStream
                .process(new KeyedProcessFunction<String, JSONObject, String>() {

                    private ValueState<JSONObject> maxPositionSec;
                    private Long ts;


                    @Override
                    public void open(Configuration parameters) throws Exception {
                        maxPositionSec = getRuntimeContext().getState(
                                new ValueStateDescriptor<JSONObject>("positionSec", JSONObject.class)
                        );
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        //超过30s则默认关闭视频
                        out.collect(maxPositionSec.value().toJSONString());
                    }

                    @Override
                     public void processElement(JSONObject json, Context ctx, Collector<String> out) throws Exception {

                         Long playSec = json.getJSONObject("appVideo").getLong("play_sec");
                         if( playSec <30){
                             out.collect(json.toJSONString());
                         }else{
                             //否则30内没来新数据则默认关闭
                             if(maxPositionSec.value() ==null){//当第一条数据来时
                                 ts = json.getLong("ts");
                                 ctx.timerService().registerEventTimeTimer(ts);
                                 maxPositionSec.update(json);
                             }else{//比较时间戳大小，来的数据时间戳比较大的话，取消原有定时器，重新注册
                                 Long time = maxPositionSec.value().getLong("ts");
                                 if(time>ts){
                                     //重新注册
                                     ctx.timerService().deleteEventTimeTimer(ts);
                                     maxPositionSec.update(json);
                                     ctx.timerService().registerEventTimeTimer(time);
                                     ts = time;
                                 }

                             }

                         }
                     }
                 }
                )
//                .print();
                .addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_VIDEO_PLAY_INFO));
               /* .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<JSONObject, String, String, TimeWindow>() {

                    private ValueState<JSONObject> maxPositionSec;//播放时间为30s倍数 且 取播放时长最长字段

                    long ts;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        maxPositionSec = getRuntimeContext().getState(
                                new ValueStateDescriptor<JSONObject>("positionSec", JSONObject.class)
                        );
                    }

                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<JSONObject> elements,
                                        Collector<String> out) throws Exception {




                        if(maxPositionSec.value() ==null){

                            List<JSONObject> list = AtguiguUtil.toList(elements);
                            JSONObject max = Collections.max(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                            
                            Long playSec = max.getJSONObject("appVideo").getLong("play_sec");
                            //如果播放时长小于30则肯定是关闭视频
                            if( playSec <30){
                                out.collect(max.toJSONString());
                            }else{
                                //否则30内没来新数据则默认关闭
                                ts = max.getLong("ts");
                                ctx.time
                            }

                        }
                    }
                });*/


        /*Pattern
                .<JSONObject>begin("key1")
                .where(new SimpleCondition<JSONObject>() {

                    @Override
                    public boolean filter(JSONObject json) throws Exception {
                        return json.getJSONObject("appVideo").getLong("play_sec") < 30;
                    }
                });*/

    }
}
